var Specialtopic = function() {


    var datalist_url = $('.datalist_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var redirect_url = $('.redirect_url').val();
    var save_url = $('.save_url').val();

    var typeDatalist_url = $('.typeDatalist_url').val();
    var saveType_url = $('.saveType_url').val();
    var delType_url = $('.delType_url').val();
    var isLoadTypeTable = false;

    var initTable = function() {
        var table = $('#data-table');

        if(table.length > 0){
            table.dataTable({
                "processing": true,
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: datalist_url,
                },
                "autoWidth": false,
                "columns": [
                    {
                        "data": "imgUrl",
                        "render": function(data, type, row, meta) {
                            return '<a href="'+data+'" target="_blank"><img src="'+data+'" style="width: 60px;height: 40px;"/></a>';
                        }
                    },
                    {"data": "title"},
                    {"data": "sorting"},
                    {
                        //"width": "15%",
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            var html = '<a href="'+edit_url+'?id='+row.id+'" type="button" class="btn btn-success">编辑</a>';
                            html += '<button type="button" class="btn btn-danger delete-btn">删除</button>';
                            html += '<button type="button" class="btn btn-info type-btn">分类</button>';

                            return html;
                        }
                    }
                ],
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": false,
                "stateSave": true,
                "stateSaveParams": function (settings, data) {
                    var search = data.search.search;
                    if(search){
                        var arr = $.parseJSON(search);
                        for(var key in arr){
                            $("#searchForm input[name='"+key+"']").val(arr[key]);
                            $("#searchForm select[name='"+key+"']").val(arr[key]);
                        }
                    }
                },
                "order": [
                    [2, "asc"]
                ],
                "columnDefs": [{
                    "orderable": false,
                    "targets": [0, 3]
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnInitComplete": function() {
                    //var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                    var city = $('input[name=city]').val();
                    if(city){
                        //$("#city").find("option:contains('"+city+"')").attr("selected", true);
                        get_xian($("#city"));
                    }
                }
            });
        }

        // 筛选
        $('#doSearch').on('click', function(event){
            var param = $('#searchForm').serializeObject();

            tableSearch(table, param);
        });

        // 分类
        table.on('click', '.type-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;

            event.preventDefault();
            $('#type-modal').modal('show');
            $('.specialtopicId').val(id);
            initTypeTable({'id':id});
        });

        // 删除
        table.on('click', '.delete-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var _this = $(this);

            var text = '是否要删除这条数据？';
            var title = '请确认';
            var confirmBtn = '确定';
            var cancelBtn = '取消';
            event.preventDefault();

            layer.confirm(
                text,
                {
                    title: title,
                    btn: [confirmBtn, cancelBtn]
                },
                function(index){
                    layer.close(index);
                    var url = delete_url;
                    var data = {'id':id};
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: data,
                        dataType : 'json',
                        success: function (data) {
                            layer.msg(data.msg);
                            if(data.code == 1){
                                _this.parents('tr').remove();
                            }
                        }
                    });
                }
            );
        });
    };

    var initTypeTable = function(params) {
        var table = $('#type-datatable');

        if(table.length > 0){
            table.dataTable({
                "processing": true,
                "ordering": false, // 禁止排序
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: typeDatalist_url,
                    data: params
                },
                "autoWidth": false,
                "columns": [
                    {"data": "name"},
                    {
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            var html = '<button type="button" class="btn btn-success edit-btn">编辑</button>';
                            html += '<button type="button" class="btn btn-danger delete-btn">删除</button>';

                            return html;
                        }
                    }
                ],
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": true,
                "stateSaveParams": function (settings, data) {
                    //
                },
                "columnDefs": [{
                    "orderable": false,
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnInitComplete": function() {
                    //var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                }
            });

            isLoadTypeTable = true;
        }

        // 添加
        $('.addType-btn').on('click', function(){
            //$(this).prop('disabled', true);
            if(table.find('.saveType-btn').length <= 0){
                table.find('.edit-btn').prop('disabled', true);
                table.find('tbody:last').append(typeTemplate);
            }
        });

        // 编辑
        table.on('click', '.edit-btn', function(event) {
            table.find('.edit-btn').prop('disabled', true);
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var name = dataArr[0].name;

            if(table.find('.saveType-btn').length <= 0){
                table.find('tbody:last').append(typeTemplate);
            }
            table.find('input[name=id]').val(id);
            table.find('input[name=name]').val(name);
        });

        // 保存
        table.on('click', '.saveType-btn', function(){
            var _this = $(this);
            var specialtopicId = $('.specialtopicId').val();
            var id = table.find('input[name=id]').val();
            var name = table.find('input[name=name]').val();

            if(name.trim() == '') {
                layer.msg('请输入分类名称');
                table.find('input[name=name]').focus();
                return false;
            }
            var data = {
                'specialtopicId' : specialtopicId,
                'id' : id,
                'name' : name
            };
            _this.prop("disabled", true);

            $.ajax({
                url : saveType_url,
                type : 'post',
                dataType : 'json',
                contentType:"application/json; charset=utf-8",
                data : JSON.stringify(data),
            }).done(function(data) {
                _this.prop("disabled", false);
                if (data.code == 1) {
                    table.DataTable().ajax.reload();
                    table.find('.edit-btn').prop('disabled', false);
                } else {
                    layer.msg(data.msg);
                }
            });
            return false;
        });

        // 取消
        table.on('click', '.cancelType-btn', function(){
            table.find('.edit-btn').prop('disabled', false);
            $(this).parent().parent().remove();
            return false;
        });

        // 删除
        table.on('click', '.delete-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var _this = $(this);

            var text = '是否要删除这条数据？';
            var title = '请确认';
            var confirmBtn = '确定';
            var cancelBtn = '取消';
            event.preventDefault();

            layer.confirm(
                text,
                {
                    title: title,
                    btn: [confirmBtn, cancelBtn]
                },
                function(index){
                    layer.close(index);
                    var url = delType_url;
                    var data = {'id':id};
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: data,
                        dataType : 'json',
                        success: function (data) {
                            layer.msg(data.msg);
                            if(data.code == 1){
                                //_this.parents('tr').remove();
                                table.DataTable().ajax.reload();
                            }
                        }
                    });
                }
            );
        });
    };

    var tableSearch = function(table, params) {

        table.DataTable().search(JSON.stringify(params)).draw();
    };


    return {
        init: function() {
            initTable();

            this.onEvent();
        },

        onEvent: function() {

            // 表单提交
            $('#form-submit').on('click', function(){
                var form = this.form;
                var _this = $(this);

                if(!form.id.value) {
                    if(form.townId.value == 0) {
                        layer.msg('请选择所在地');
                        return;
                    }
                }
                if(form.title.value.trim() == '') {
                    layer.msg('请输入专题标题');
                    form.title.focus();
                    return;
                }
                if(form.title.value.length > 40){
                    layer.msg('专题标题最多为40个字符');
                    form.title.focus();
                    return false;
                }
                if(form.imgUrl.value.trim() == ''){
                    layer.msg('请上传封面图');
                    return false;
                }

                var _data = $(form).serializeObject();
                _this.prop("disabled", true);

                $.ajax({
                    url : save_url,
                    type : 'post',
                    dataType : 'json',
                    contentType : "application/json; charset=utf-8",
                    data : JSON.stringify(_data),
                }).done(function(data) {
                    _this.prop("disabled", false);
                    if (data.code == 1) {
                        layer.msg('保存成功');
                        window.location.href = data.url;
                    } else if (data.code === 0 ) {
                        layer.msg(data.msg);
                    }
                });
            });
        }

    };

}();

jQuery(document).ready(function() {
    Specialtopic.init();

});

//轮播图
var typeTemplate = stringLines(function(){/*
	<tr>
		<td>
            <input type="text" class="form-control" name="name" maxlength="80" value="" />
	    </td>
	    <td>
	        <input type="hidden" class="form-control" name="id" value="" />
	        <button type="button" class="btn green saveType-btn">保存</button>
	        <button type="button" class="btn default cancelType-btn">取消</button>
	    </td>
	</tr>
*/});
